//
//  MNetworkHandler.m
//  MobiProject
//
//  Created by 阔 李 on 15-3-25.
//  Copyright (c) 2015年 阔 李. All rights reserved.
//

#import "MNetworkHandler.h"
#import "MNetworkItem.h"
#import "AFNetworking.h"


#import <MobileCoreServices/MobileCoreServices.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperationManager.h"
#import <Availability.h>

@implementation MNetworkHandler

+ (MNetworkHandler *) sharedInstance
{
    static MNetworkHandler * handler = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        handler = [[MNetworkHandler alloc] init];
    });
    
    return handler;
}

- (BOOL)cancelForDelegate:(id)delelgate
{
    NSUInteger hashValue = [delelgate hash];
    
    BOOL flag = NO;
    
    for (MNetworkItem *item in self.networkItems)
    {
        if (item.hashValue == hashValue) 
        {
            [self removeItem:item];
            flag = YES;
        }
    }
    
    return flag;
}

- (void)addItem:(MNetworkItem *)networkItem
{
    if (networkItem.showHUD) 
    {
        _showHUDReqCount++;
    }
    
    [self.networkItems addObject:networkItem];
}

- (void)removeItem:(MNetworkItem *)networkItem
{
    if (networkItem.showHUD) 
    {
        _showHUDReqCount--;
    }
    
   // [networkItem.httpRequest clearDelegatesAndCancel];
    [self.networkItems removeObject:networkItem];
}

- (NSUInteger)conURL:(NSString *) url
         networkType:(NetWorkType) networkType
              params:(NSMutableDictionary *) params
            delegate:(id) delegate
             showHUD:(BOOL) showHUD
        successBlock:(NWSuccessBlock) successBlock
        failureBlock:(NWFailureBlock) failureBlock
{
    /// 如果有一些公共处理，可以写在这里
    
    
    NSUInteger hashValue = [delegate hash];
    MNetworkItem *item = [[MNetworkItem alloc] initWithtype:networkType
                                                          url:url
                                                       params:params
                                                     delegate:delegate
                                                    hashValue:hashValue
                                                      showHUD:showHUD
                                                 successBlock:successBlock
                                                 failureBlock:failureBlock];
    return item.hashValue;
}

- (void)UPLOAD_IMAGES:(NSArray<UIImage *> *)imageArr
                 Path:(NSString *)path
                 pram:(NSMutableDictionary *)params
             progress:(ProgressBlock)progress
              success:(NWSuccessBlock)success
              failure:(NWFailureBlock)failure{


    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/plain",
                                                         @"text/javascript",
                                                         @"text/json",
                                                         @"text/html",
                                                         @"image/jpeg", nil];
    [manager POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        
        
        if(imageArr){
            
            __block NSInteger i = 0;
            
            [imageArr enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                //压缩图片
                
                i++;
                
                // NSData *imageData = UIImagePNGRepresentation(obj);
                
                NSData *imageData = UIImageJPEGRepresentation(obj,0.005);
            
            
                
                //压缩图片
            
                
                //拼接图片名称+时间确保不重复命名
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                
                formatter.dateFormat = @"yyyyMMddHHmmss";
                
                NSString *imageFileName = [NSString stringWithFormat:@"%@%ld.jpg", [formatter stringFromDate:[NSDate date]],i];
                
                // 测试输出文件名
            
                
                //上传图片，以文件流的格式
            
            
                
                [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"image%ld",i] fileName:imageFileName mimeType:@"image/JPG"];
                            
                            
                        }];
                    }

        
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *strtmp = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *requestTmp = [NSString stringWithString: strtmp];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];  //解析

        NSLog(@"+++>%@", resultDic);
        
        NSLog(@"--->%@", resultDic[@"msg"]);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"--->%@", error);
    }];



}
@end
